<template>
    <ScaleBox :width="1920" :height="1080" bgc="transparent" :delay="0" :isFlat="false">
        <div class="main" v-loading="loading" :element-loading-svg="svg" element-loading-svg-view-box="-10, -10, 50, 50"
            element-loading-background="rgba(4,11,18,0.99)">
            <el-row class="row">
                <el-col :span="5">
                    <More :data="configData" />
                    <OptionData v-if="leftData" :data="leftData" />
                </el-col>
                <el-col :span="13" class="col14">
                    <Statistics v-if="topData" :data="topData" style="flex: 5;" />
                    <Map style="flex: 20;" v-if="mapData.length" :data="mapData" />
                    <Tip style="flex: 1;" :data="moreData" v-if="moreData.length" />
                </el-col>
                <el-col :span="6" class="c-6">
                    <div style="flex: 5;">
                        <ZChart :data="contrastData" v-if="contrastData" />
                    </div>
                    <div style="flex: 5;">
                        <RealTime :data="sData" />
                    </div>
                    <div style="flex: 2;">
                        <Breakdown :data="equipmentData" v-if="equipmentData.length" />
                    </div>
                </el-col>
            </el-row>
        </div>
    </ScaleBox>
</template>

<script setup>
import { ElLoading } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { WEB_URL } from '../../utils/init'
import ScaleBox from "vue3-scale-box";
import OptionData from './components/optionData.vue'
import Map from './components/map.vue';
import More from './components/more.vue';
import Statistics from './components/statistics.vue'
import Tip from './components/tip.vue';
import ZChart from './components/zChart.vue';
import RealTime from './components/realTime.vue';
import Breakdown from './components/breakdown.vue'

import { getconfig, getLeftTop, getMap, getContrast, getEquipment } from '../../api/apiList'


// 获取基础配置
let configData = ref({})
const getConfigData = () => {
    return new Promise(async (resolve, reject) => {
        const res = await getconfig()
        if (res.code = 200) {
            configData.value = res.data
            configData.value.logo = WEB_URL + configData.value.logo
            resolve('ok')
        }
    })
}

// 获取左边和顶部
let leftData = ref()
let topData = ref()
const getLeftTopData = () => {
    return new Promise(async (resolve, reject) => {
        const res = await getLeftTop()
        if (res.code == 200) {
            const { data1, data2, data3, data4, data5, data6, data7, data8, data9 } = res.data
            topData.value = {
                data7,
                data8,
                data9
            }
            leftData.value = {
                data1, data2, data3, data4, data5, data6
            }
            resolve('ok')
        }
    })
}

// 获取地图点
let mapData = ref([])
let moreData = ref([])
const getMapData = () => {
    return new Promise(async (resolve, reject) => {
        const res = await getMap()
        if (res.code == 200) {
            mapData.value = res.data
            mapData.value.forEach(item => {
                item.data.forEach(k => {
                    k.name = k.title
                    k.value = [Number(k.content.split(',')[0]), Number(k.content.split(',')[1])]
                })
                moreData.value.push(item.title)
            })
            resolve('ok')
        }
    })
}

// 充电人数对比
let contrastData = ref()
const getContrastData = () => {
    return new Promise(async (resolve, reject) => {
        const res = await getContrast()
        let time = []
        let yesToday = []
        let today = []
        if (res.code == 200) {
            res.data[0].data.forEach(item => {
                time.push(item.time_num)
                yesToday.push(item.number)
            })
            res.data[1].data.forEach(item => today.push(item.number))
            contrastData.value = { time, yesToday, today }
            resolve('ok')
        }
    })
}

// 故障设备
const equipmentData = ref([])
const getEquipmentData = () => {
    return new Promise(async (resolve, reject) => {
        const res = await getEquipment()
        if (res.code == 200) {
            equipmentData.value = res.data
            resolve('ok')
        }
    })
}

let sData = ref([])
onMounted(async () => {
    getWindowResize()
    await init()
    const sDataRes = await getData()
    sData.value = sDataRes
    setInterval(() => {
        setTimeout(async () => {
            // sDataRes.value = []
            const sDataRes = await getData()
            sData.value = sDataRes
        }, 0)
    }, 2000)
    setInterval(() => {
        setTimeout(() => {
            location.reload()
        }, 0)
    }, 5 * 60 * 1000)

})

// 获取屏幕尺寸
// 屏幕宽度
const windowWidth = ref(1920)
// 屏幕高度
const windowHeight = ref(1080)
const getWindowResize = function () {
    windowWidth.value = window.innerWidth
    windowHeight.value = window.innerHeight
    console.log(windowWidth.value, 'w')
    console.log(windowHeight.value, '')
}

const loading = ref(true)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(1, 11, 20, 1)"/>`
const init = async () => {
    // getConfigData()
    // getLeftTopData()
    // getMapData()
    // getContrastData()
    // getEquipmentData()

    const queue = [
        getConfigData(),
        getLeftTopData(),
        getMapData(),
        getContrastData(),
        getEquipmentData()
    ]
    await Promise.all(queue)
    loading.value = false
}

// 实时充电数据
let number = 5

function getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function generateRandomMilliseconds(min, max) {
    const randomMilliseconds = Math.floor(Math.random() * (max - min + 1)) + min;
    return randomMilliseconds;
}

function generateTimeData(startMinutes, endMinutes, n = 10) {
    // 转换为秒  
    const startSeconds = startMinutes * 60;
    const endSeconds = endMinutes * 60;
    // 获取当前时间（Date对象）  
    const now = new Date();
    // 创建一个数组来存储Date对象  
    const dates = [];
    // 生成第一条数据的时间  
    const randomIntervalForFirst = Math.floor(Math.random() * (endSeconds - startSeconds + 1)) + startSeconds;
    const firstDate = new Date(now.getTime() - randomIntervalForFirst * 1000);
    dates.push(firstDate);
    // 生成剩余的数据  
    for (let i = 1; i < n; i++) {
        // 随机间隔（秒为单位）  
        const randomInterval = Math.floor(Math.random() * (endSeconds - startSeconds + 1)) + startSeconds;
        // 确保新的时间不超过前一条数据的时间  
        const newDate = new Date(dates[i - 1].getTime() - randomInterval * 1000);
        // 如果新时间超过了当前时间，则使用当前时间  
        if (newDate > now) {
            newDate > now ? dates.unshift(new Date(now)) : dates.unshift(newDate);
        } else {
            dates.unshift(newDate);
        }
    }
    return dates.sort((a, b) => a - b);
    // return dates;
}


function generateTimes(n) {
    const { start_min, end_min } = configData.value
    const randomNumber = getRandomNumber(Number(start_min), Number(end_min))
    const a = generateTimeData(Number(start_min), Number(end_min))
    console.log(a, 'aasss')

    let ajaxMillisecond = randomNumber * 60 * 1000
    let ajaxSeconds = randomNumber * 60
    const resultTime = generateRandomMilliseconds(ajaxMillisecond, 0)
    const times = [];
    let currentTime = new Date();
    for (let i = 0; i < n; i++) {
        const randomSeconds = Math.floor(Math.random() * ajaxSeconds);
        // randomSeconds * 1000
        currentTime = new Date(currentTime.getTime() - ajaxMillisecond);
        times.push(currentTime);
    }
    return times.sort((a, b) => a - b);
}

// 时间格式化
function formatTime(date) {
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    const formattedHours = hours < 10 ? '0' + hours : hours;
    const formattedMinutes = minutes < 10 ? '0' + minutes : minutes;
    const formattedSeconds = seconds < 10 ? '0' + seconds : seconds;

    return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}


// 随机生成手机号码
function generateRandomPhoneNumbers(count) {
    // 定义手机号码开头的数组  
    const prefixes = ["130", "131", "132", "133", "135", "137", "138", "170", "187", "189"];
    const numbers = '0123456789';
    const phoneNumbers = [];
    for (let i = 0; i < count; i++) {
        // 随机选择一个手机号码开头  
        const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
        // 生成剩余的9位数字  
        let rest = '';
        for (let j = 0; j < 8; j++) {
            rest += numbers[Math.floor(Math.random() * numbers.length)];
        }
        // 拼接手机号码并隐藏中间四位  
        const fullPhoneNumber = prefix + rest;
        const maskedPhoneNumber = fullPhoneNumber.slice(0, 3) + '****' + fullPhoneNumber.slice(-4);
        // 添加到结果数组中  
        phoneNumbers.push(maskedPhoneNumber);
    }
    return phoneNumbers;
}

function getData() {
    return new Promise((resolve, reject) => {
        const { start_min, end_min } = configData.value
        // let time = generateTimes(number)
        let time = generateTimeData(Number(start_min), Number(end_min), number)
        let phone = generateRandomPhoneNumbers(number)
        let timeArr = []
        time.forEach(item => timeArr.push(formatTime(item)))
        let sData = timeArr.map((item, index) => {
            return {
                phoneNumber: phone[index],
                timeStr: item
            }
        })
        resolve(sData)
    })
}


</script>

<style scoped lang="scss">
.main {
    padding: 30px 0 30px 0;
    background: url(../../assets/image/bg.png) no-repeat;
    background-size: cover;
    width: 100%;
    height: 100%;

    .col14 {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;

    }

    .c-6 {
        // padding: 39px 0 84px 0;
        display: flex;
        flex-direction: column;
        justify-content: center;

        overflow: hidden;
    }

    .row {
        width: 100%;
        height: 100%;
    }

    .box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-direction: column;
    }
}
</style>
